package com.example.foo.member.service;

import java.math.BigDecimal;

import org.springframework.transaction.annotation.Transactional;

import com.example.foo.member.model.Withdraw;
import com.example.foo.account.model.Account;
import com.example.foo.account.service.AccountService;
import com.example.foo.member.WithdrawException;

@org.springframework.stereotype.Service
public class WithdrawFacadeService {

	private final AccountService accountService;
	private final WithdrawService withdrawService;

	public WithdrawFacadeService(AccountService accountService,
			WithdrawService withdrawService) {
		this.accountService = accountService;
		this.withdrawService = withdrawService;
	}

	// ========== WithdrawFacade ==========

	@Transactional(timeout = 60, rollbackFor = Exception.class)
	public void createWithdrawPending(String bankName, String bankBranchName, String cardHolder, String cardNumber, BigDecimal money, BigDecimal serviceFee, Long userId) {
		accountService.updateAccountDecrement(Account.Acctc.pinmoney, "提现", money, userId, "Withdraw", 0L);
		withdrawService.createWithdrawPending(bankName, bankBranchName, cardHolder, cardNumber, money, serviceFee, userId);
	}

	@Transactional(timeout = 60, rollbackFor = Exception.class)
	public void updateWithdrawSuccess(Long id, String memo) {
		Withdraw withdraw = withdrawService.findWithdrawById(id);
		if (withdraw.getState() != Withdraw.State.pending) {
			throw new WithdrawException(String.format("状态错误: %s", withdraw.getState().text));
		}

		withdrawService.updateWithdrawSuccess(id, memo);
	}

	@Transactional(timeout = 60, rollbackFor = Exception.class)
	public void updateWithdrawFailure(Long id, String memo) {
		Withdraw withdraw = withdrawService.findWithdrawById(id);
		if (withdraw.getState() != Withdraw.State.pending) {
			throw new WithdrawException(String.format("状态错误: %s", withdraw.getState().text));
		}

		withdrawService.updateWithdrawFailure(id, memo);

		BigDecimal value = withdraw.getMoney();
		Long userId = withdraw.getUserId();
		String relType = "Withdraw";
		Long relId = withdraw.getId();
		accountService.updateAccountIncrement(Account.Acctc.pinmoney, "提现退回", value, userId, relType, relId);
	}

	@Transactional(timeout = 60, rollbackFor = Exception.class)
	public void updateWithdrawFinish(Long id, String memo) {
		Withdraw withdraw = withdrawService.findWithdrawById(id);
		if (withdraw.getState() != Withdraw.State.success) {
			throw new WithdrawException(String.format("状态错误: %s", withdraw.getState().text));
		}

		withdrawService.updateWithdrawFinish(id, memo);
	}

}
